package tw.cuttle.view;

import java.io.IOException;
import java.io.StringWriter;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.context.Context;

import tw.cuttle.CuttleContext;
import tw.cuttle.process.EvaluateViewSupport;

public class VelocitySupport extends EvaluateViewSupport {

    @Override
    protected String evaluate(String view) {
	Context context=new VelocityContext();
	while(CuttleContext.getActionContext().getActionHelper().getRequest().getAttributeNames().hasMoreElements()){
	    Object obj=CuttleContext.getActionContext().getActionHelper().getRequest().getAttributeNames().nextElement();
	    context.put((String)obj, CuttleContext.getActionContext().getActionHelper().getRequest().getAttribute((String)obj));
	}
	StringWriter sw=new StringWriter();
	String content=null;
	try {
	    Template template=Velocity.getTemplate(view);
	    template.merge(context, sw);
	    content=sw.toString();
	} catch (Exception e) {
	    e.printStackTrace();
	    throw new RuntimeException(e);
	}finally{
	    try {
		sw.close();
	    } catch (IOException e) {
		e.printStackTrace();
	    }
	}
	return content;
    }

}
